<?php

class Email
{
	private $error;
	public function __construct()
	{}

	public function get_contacts($account, $password)
	{
		$account = current(explode('@', $account));
		$account = strtolower(trim($account));
		$password = trim($password);
		if (empty($account) || empty($password)) {
			$this->error = 'err_01';
			return false;
		}
		$account .= '@gmail.com';

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_TIMEOUT, 3);
		curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/accounts/ClientLogin');
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, 'accountType=GOOGLE&Email=' . $account . '&Passwd=' . $password . '&service=cp&source=51.COM-InviteProject-0.1');
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_NOBODY, false);
		$return = curl_exec($ch);
		curl_close($ch);

		$sid = $lsid = $auth = '';
		$lines = explode("\n", $return);
		foreach ($lines as $line) {
			if (preg_match('/^SID=(.*?)$/', trim($line), $m)) {
				$sid = $m[1];
			}
			if (preg_match('/^LSID=(.*?)$/', trim($line), $m)) {
				$lsid = $m[1];
			}
			if (preg_match('/^Auth=(.*?)$/', trim($line), $m)) {
				$auth = $m[1];
			}
		}
		if (empty($sid) || empty($lsid) || empty($auth)) {
			$this->error = 'err_01';
			return false;
		}

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_TIMEOUT, 3);
		curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/m8/feeds/contacts/' . $account . '/full?alt=json');
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: GoogleLogin auth=' . $auth));
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_NOBODY, false);
		$return = curl_exec($ch);
		curl_close($ch);

		$json_obj = json_decode($return);
		if (!is_object($json_obj)) {
			$this->error = 'err_02';
			return false;
		}

		$entries = $json_obj->feed->entry;
		$contacts = array();
		foreach ($entries as $entry) {
			$tmp = array();
			$tmp['email'] = iconv('UTF-8', 'GBK', $entry->{'gd$email'}[0]->address);
			$tmp['name'] = $entry->title->{'$t'} ? iconv('UTF-8', 'GBK', $entry->title->{'$t'}) : current(explode('@', $tmp['account']));
			array_push($contacts, $tmp);
		}
		if (!count($contacts)) {
			$this->error = 'err_02';
			return false;
		}
		return $contacts;
	}

	public function get_error()
	{
		return $this->error;
	}
}

?>